package com.yuelao.util;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @author FLY
 * @version v1.0
 * @project yuelao-server
 * @date 2017/9/12 16:13
 * @修改记录 版本       修改人         修改时间         修改内容描述
 * --------------------------------------------------
 * <p>
 * --------------------------------------------------
 */
public class BeanMapEx {
    public static Object convertMap2Bean(Class type, Map map)
    //	throws IntrospectionException, IllegalAccessException, InstantiationException, InvocationTargetException
    {
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(type); // 获取类属性
            Object obj;
            obj = type.newInstance();
            /**
             * 得到所用属性类型
             */
            Class<?> clz = obj.getClass();
            Field[] fields = clz.getDeclaredFields();
            Map<String, String> typeMap = new HashMap<String, String>();
            for (Field field : fields) {
                //属性名field.getName();
                //属性类型field.getType().toString();
                typeMap.put(field.getName(), field.getType().toString());
            }

            // 创建 JavaBean 对象
            // 给 JavaBean 对象的属性赋值
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (int i = 0; i < propertyDescriptors.length; i++) {
                PropertyDescriptor descriptor = propertyDescriptors[i];
                String propertyName = descriptor.getName();
                if (map.containsKey(propertyName)) {
                    // 下面一句可以 try 起来，这样当一个属性赋值失败的时候就不会影响其他属性赋值。
                    Object value = map.get(propertyName);
                    if (value != null) {
                        //判断属性类型，并进行比对调整
                        String newType = typeMap.get(propertyName);
                        String requestType = value.getClass().toString();
                        if (!requestType.equals(newType)) {
                            //value = Integer.parseInt(value.toString());
                            if (newType.equals("class java.lang.Integer")) {
                                value = Integer.parseInt(value.toString());
                            }
                            if (newType.equals("class java.util.Date")
                                    && requestType.equals("class java.lang.String")) {
                                Date date = new Date(Long.parseLong(value.toString()));
                                value = date;
                            }

                        }
                    }

                    Object[] args = new Object[1];
                    args[0] = value;
                    descriptor.getWriteMethod().invoke(obj, args);
                }
            }
            return obj;
        } catch (

                Exception e)

        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 将一个 JavaBean 对象转化为一个 Map
     *
     * @param bean 要转化的JavaBean 对象
     * @return 转化出来的 Map 对象
     * @throws IntrospectionException    如果分析类属性失败
     * @throws IllegalAccessException    如果实例化 JavaBean 失败
     * @throws InvocationTargetException 如果调用属性的 setter 方法失败
     */
    public static Map convertBean2Map(Object bean)
            throws IntrospectionException, IllegalAccessException, InvocationTargetException {
        Class type = bean.getClass();
        Map returnMap = new HashMap();
        BeanInfo beanInfo = Introspector.getBeanInfo(type);

        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (int i = 0; i < propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();
            if (!propertyName.equals("class")) {
                Method readMethod = descriptor.getReadMethod();
                Object result = readMethod.invoke(bean, new Object[0]);
                if (result != null) {
                    returnMap.put(propertyName, result);
                } else {
                    returnMap.put(propertyName, "");
                }
            }
        }
        return returnMap;
    }

    /**
     * 获取bean值
     *
     * @param bean
     * @return
     * @throws IntrospectionException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public static List getBeanKey(Object bean) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
        Class type = bean.getClass();
        BeanInfo beanInfo = Introspector.getBeanInfo(type);
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        List keyList = new ArrayList<>();
        for (int i = 0; i < propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();
            if (!propertyName.equals("class")) {
                Method readMethod = descriptor.getReadMethod();
                Object result = readMethod.invoke(bean, new Object[0]);
                if (result != null) {
                    keyList.add(result);
                } else {
                    keyList.add("");
                }
            }
        }
        return keyList;
    }

}
